package core

import (
	"io"
	"net/url"
	"regexp"
)

func getNmxxAuthUrl() (string, error) {
	resp, err := client.Get(originUrl)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	content := string(body)
	//<script>top.self.location.href='http://172.18.200.201/eportal/index.jsp?wlanuserip=d408584c26966be9cde13a99df61e01f&wlanacname=f44ef2c32c83f08c75b268f93113bc72&ssid=&nasip=e6957ba0361b5c70e4820667d533fff8&snmpagentip=&mac=d049ecda47fba258ab1386051646d31d&t=wireless-v2&url=cd1458b3c353c25dff7bb9fc9dd8cda25ccea2d8ff1ccc33&apmac=&nasid=f44ef2c32c83f08c75b268f93113bc72&vid=250f02ed6b9f364f&port=94465763a3f9789f&nasportid=f5eb983692924fa26e6431fe9df4835f5fe3bc35e3602b4c24da24ebd0d706459322743450686f9c'</script>
	reg := regexp.MustCompile(`'(.*?)'`)
	matches := reg.FindStringSubmatch(content)
	if len(matches) > 1 {
		return matches[1], nil
	} else {
		return "", nil
	}
}

func LoginNMXX(userId, password string) (string, error) {
	nextUrlStr, err := getNmxxAuthUrl()
	if err != nil {
		return "", err
	}

	if nextUrlStr == "" {
		return "", ErrLoggedIn
	}

	nextUrl, err := url.Parse(nextUrlStr)
	if err != nil {
		return "", err
	}

	query := url.Values{}
	query.Set("userId", userId)
	query.Set("password", password)
	query.Set("queryString", nextUrl.Query().Encode())

	authUrl := nextUrl.Scheme + "://" + nextUrl.Host + "/eportal/InterFace.do?method=login"

	resp, err := client.PostForm(authUrl, query)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	bytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(bytes), nil
}
